package fengcan;

import java.io.IOException;
import java.io.OutputStream;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Types;

import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.binary.Hex;

import Entity.WcsDvcEntity;
import log.WcsLog;
import utils.DbUnits;
import utils.LogUnits;

/**
 * 该线程调用存储过程,在线程池中使用
 * @author 风蚕
 *
 */
class ProduceThread extends Thread {
	
	private WcsLog logger;
	
	WcsDvcEntity wcs;
	OutputStream os;
	String msg;
	
	public ProduceThread(WcsDvcEntity wcs,OutputStream os,String msg) {
		this.wcs = wcs;
		this.os = os;
		this.msg = msg;
		this.logger = LogUnits.getLogger(ProduceThread.class, wcs);
	}
	
	@Override
	public void run() {
		Connection conn = null;
		try {
			conn = DbUnits.getConnection();
			String sql = "{call " + wcs.getRevProc() + "(?,?,?,?,?,?)}";
			CallableStatement smAnalysisPlcMsgCall  = conn.prepareCall(sql);
			smAnalysisPlcMsgCall.setInt(1, wcs.getDvcId());
			smAnalysisPlcMsgCall.setString(2, msg);
			smAnalysisPlcMsgCall.registerOutParameter(3, Types.VARCHAR);
			smAnalysisPlcMsgCall.registerOutParameter(4, Types.INTEGER);
			smAnalysisPlcMsgCall.registerOutParameter(5, Types.VARCHAR);
			smAnalysisPlcMsgCall.registerOutParameter(6, Types.LONGVARCHAR);
			smAnalysisPlcMsgCall.execute();
			String s_send = smAnalysisPlcMsgCall.getString(3);
			String s_msg = smAnalysisPlcMsgCall.getString(6);
			if (s_send.length() != 0) {
				os.write(Hex.decodeHex(s_send));
			}
			if (!s_msg.equals("")) {
				logger.info("返回参数:"+s_msg);
			}
			
		} catch (SQLException e) {
			logger.error("数据库错误，存储过程连接调用失败！");
			e.printStackTrace();
		} catch (IOException e) {
			logger.error("io流写出失败");
			e.printStackTrace();
		} catch (DecoderException e) {
			logger.error("16进制转化失败！");
			e.printStackTrace();
		}finally {
			try {
				conn.close();
			} catch (SQLException e) {
				logger.error("connection连接关闭失败！");
				e.printStackTrace();
			}
		}
		
		
	}
}

